package com.jhg.drgclinicalpathway;

import com.alibaba.fastjson.JSON;
import com.jhg.drgclinicalpathway.dao.sys.AccountDao;
import com.jhg.drgclinicalpathway.domain.RpnMsg;
import com.jhg.drgclinicalpathway.domain.sys.AccountInfo;
import com.jhg.drgclinicalpathway.utils.JWTUtils;
import com.jhg.drgclinicalpathway.utils.PassToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.naming.Name;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class JwtAuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    AccountDao accountDao;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest,
                             HttpServletResponse httpServletResponse,
                             Object object) throws Exception {
        // 从请求头中取出 token  这里需要和前端约定好把jwt放到请求头一个叫token的地方
        String token = httpServletRequest.getHeader("X-Access-Token");
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();

        httpServletResponse.setContentType("application/json");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //默认全部检查
        else {
            // 执行认证
            if (token == null) {
                //这里其实是登录失效,没token了   这个错误也是我自定义的，读者需要自己修改
               try {
                   httpServletResponse.getWriter().write(JSON.toJSONString(RpnMsg.FAIL("请先登录！")));
               }catch (Exception ex){}
            }

            // 获取 token 中的 user Name
            if(StringUtils.isEmpty(token)){
                return true;
            }
            String userid = JWTUtils.getClaimByName(token,"userid").asString();
            String username=JWTUtils.getClaimByName(token,"username").asString();
            //找找看是否有这个user   因为我们需要检查用户是否存在，读者可以自行修改逻辑
            AccountInfo user = accountDao.findByUserName(username);
            if (user == null) {
                //这个错误也是我自定义的
                throw new Exception("登录帐号错误！");
            }

            // 验证 token
//            JWTUtils.verify(token,password);

            //获取载荷内容
//            String userName = JwtUtils.getClaimByName(token, "userName").asString();
//            String realName = JwtUtils.getClaimByName(token, "realName").asString();

            //放入attribute以便后面调用
            httpServletRequest.setAttribute("username", username);
            httpServletRequest.setAttribute("userid", userid);
            return true;

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}

